package com.study.shengsiyuan.example10;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NewIOServer {
	public static void main(String[] args) throws IOException {
		InetSocketAddress address =new InetSocketAddress(8899);
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//		serverSocketChannel.bind(address);
		ServerSocket serverSocket = serverSocketChannel.socket();
		//
		// 当tcp连接关闭后，还会保持一段时间的连接，这个状态就是超时状态（ time wait ）
		// 当前 socket处于超时状态下，其他socket无法连接此端口
		// 此方法可以使其他socket 可以连接 处于超时状态的端口。
		serverSocket.setReuseAddress(true);
		serverSocket.bind(address);

		ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
		while(true) {
			//accept（）方法返回的SocketChannel 一定是阻塞的。
			SocketChannel socketChannel = serverSocketChannel.accept();
			socketChannel.configureBlocking(true);
			int readCount =0;
			while(-1!=readCount) {
				try {
					readCount = socketChannel.read(byteBuffer);

				}catch (Exception e) {
					// TODO: handle exception
				}
				//使 position 指针复位，并没有改变limit指针位置
				byteBuffer.rewind();

			}
		}
	}
}
